<!doctype html>
<html lang="en" ng-app="BillsApp">
  <meta charset="utf-8">
  <head>
    <link href='http://twitter.github.com/bootstrap/assets/css/bootstrap.css' rel='stylesheet' />
    <link href='http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css' rel='stylesheet' />
    <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
    <script type='text/javascript' src="http://code.angularjs.org/1.0.3/angular-resource.js"></script>
    <script type='text/javascript'>
      var BillsApp = angular.module('BillsApp', ['ngResource']);
      BillsApp.filter('list', function() {
        return function(input) {
          return input.join(", ");
        }
      });
      BillsApp.controller('BillsCtrl', function($scope, $resource) {
        var Bill = $resource('/api/bills/:Id', {Id:'@Id'});
        var User = $resource('/api/users/:Id', {Id:'@Id'});
        var cursor = "", next_cursor = "", cursors = [];
        $scope.more = $scope.less = false;
        function list_bills() {
          Bill.query({
            filter: "OR(owners=="+$scope.me.Id+",viewers=="+$scope.me.Id+")",
            order: "-date,__key__",
            page_size: 100,
            cursor: cursor
          }, function(bills, h) {
            $scope.more = h("More") == "true" ? true : false;
            $scope.less = cursors.length > 0 ? true : false;
            next_cursor = h("Cursor");
            $scope.bills = bills;
            if (bills.length > 0) {
              $scope.bill.participants = bills[0].participants.join(", ")
            }
            var friendMap = {};
            bills.forEach(function(v,i) {
              var x = friendMap[v.payer] || 0;
              friendMap[v.payer] = x - v.amount;
              v.participants.forEach(function(friend) {
                var y = friendMap[friend] || 0;
                friendMap[friend] = y + v.amount/v.participants.length;
              });
            });
            $scope.people = [];
            for (var k in friendMap) {
              if (k != $scope.me.email) {
                var v = friendMap[k];
                $scope.people.push({email:k, amount:v});
              }
            }
          });
        }
        $scope.login = {};
        User.get({Id: 'me'}, function(me, h) {
          if (me.$firstlogin) {
            me.$save();
          }
          $scope.login.text = "logout";
          $scope.login.url = "/api/logout?url="+location.pathname+location.search;
          $scope.bill.participants = [me.email];
          $scope.me = me;
          list_bills();
          }, function(err) {
            $scope.login.text = "login";
            $scope.login.url = "/api/login?url="+location.pathname+location.search;
          }
        );
        $scope.bill = new Bill();
        $scope.add = function() {
          var bill = $scope.bill;
          $scope.clear();
          bill.date = Date.now();
          bill.payer = $scope.me.email;
          if (typeof bill.participants == "string") {
            bill.participants = bill.participants.split(/,\W*/);
          }
          var times = bill.participants.length;
          var save = function() {
            if (--times < 1) {
              bill.$save(function() { list_bills(); });
            }
          };
          var email = $scope.me.email;
          bill.participants.forEach(function(e) {
              User.query({filter: "email=="+e}, function(users) {
                if (users.length > 0) {
                  var u = users[0];
                  bill.viewers = bill.viewers || [];
                  var idx = bill.viewers.indexOf(u.Id);
                  if (idx < 0) {
                    bill.viewers.push(u.Id);
                  }
                }
                save();
              });
          });
        };
        $scope.clear = function() {
          $scope.bill = new Bill();
        }
        $scope.delete = function(bill) {
          $scope.bills.splice($scope.bills.indexOf(bill), 1);
          bill.$delete(function() { list_bills(); });
        }
        $scope.next = function() {
          cursors.push(next_cursor);
          cursor = next_cursor;
          list_bills();
        }
        $scope.previous = function() {
          cursors.pop();
          cursor = cursors[cursors.length-1] || "";
          list_bills();
        }
      });
    </script>
  </head>
  <body ng-controller="BillsCtrl">
    <div class="navbar">
      <div class="navbar-inner">
        <div class="container">
          <ul class="nav pull-right">
            <li><span id="user-name">{{me.email}}</span><a id="registration" href="{{login.url}}">{{login.text}}</a></li>
          </ul>
        </div>
      </div>
    </div>
    <div class="container">
      <h3>Bills with Friends</h3>
      <div id="personal">
        <div class="form-actions">
        <h4>Add a new Bill</h4>
          <form id="add-bill" ng-submit="add()">
            <ul class="inline unstyled">
              <li>
                <div class="input-prepend">
                  <span class="add-on"><i class="icon-info-sign"></i></span>
                  <input ng-model="bill.purpose" required="required" class="span3 purpose" type="text" placeholder="comcast" tabindex="1">
                </div>
              </li>
              <li>
                <div class="input-prepend">
                  <span class="add-on"><i class="icon-envelope"></i></span>
                  <input ng-model="bill.participants" required="required" class="span3 participants" type="text" placeholder="a@email.com, b@email.com" tabindex="2">
                </div>
              </li>
              <li>
                <div class="input-append input-prepend">
                  <span class="add-on">$</span>
                  <input ng-model="bill.amount" required="required" class="span1 amount" type="number" placeholder="25" tabindex="3">
                  <span class="add-on">.00</span>
                </div>
              </li>
            </ul>
            <button type="submit" class="btn btn-primary">Submit</button>
            <button ng-click="clear()" type="button" class="btn clear-bill">Clear</button>
          </form>
        </div>
        <h4>Debts</h4>
        <table class="table table-striped table-condensed table-bordered" id="bills">
          <thead>
            <tr>
              <td>Person</td>
              <td>Amount</td>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="person in people">
              <td>{{person.email}}</td>
              <td>{{person.amount | currency}}</td>
            </tr>
          </tbody>
        </table>
        <h4>Bills</h4>
        <table class="table table-striped table-condensed table-bordered" id="bills">
          <thead>
            <tr>
              <td>Purpose</td>
              <td>Participants</td>
              <td>Amount</td>
              <td>Delete</td>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="bill in bills">
              <td>{{bill.purpose}}</td>
              <td>{{bill.participants | list}}</td>
              <td>{{bill.amount | currency}}</td>
              <td><a ng-click="delete(bill)"><i class="icon-trash"></i></a></td>
            </tr>
          </tbody>
        </table>
        <a ng-show="less" ng-click="previous()">previous</a>
        <a ng-show="more" ng-click="next()">next</a>
      </div>
    </div>
  </body>
</html>
